package edu.cmu.aes.project2.ws.data;

import java.io.IOException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService()
public class UserInformationService {
	private Logger loginLog;
	private FileHandler fh;

	public UserInformationService() {
		LogManager lm = LogManager.getLogManager();
		try {
			fh = new FileHandler("login_log.txt", true);
			fh.setFormatter(new SimpleFormatter());
			loginLog = Logger.getLogger(getClass().getName());
			lm.addLogger(loginLog);
			loginLog.setLevel(Level.INFO);
			loginLog.addHandler(fh);
		} catch (SecurityException e) {
			e.printStackTrace();
			loginLog = null;
			fh = null;
		} catch (IOException e) {
			e.printStackTrace();
			loginLog = null;
			fh = null;
		}
	}

	@Override
	protected void finalize() throws Throwable {

		if (fh != null)
			fh.close();
		super.finalize();
	}

	@WebMethod()
	public UserInformationDto getUserInformation(String userName) {

		UserInformationDao userInfoDao = new UserInformationDao();
		return userInfoDao.getUserInformation(userName);
	}

	@WebMethod()
	public Boolean authentication(String userName, String password) {
		UserInformationDao userInfoDao = new UserInformationDao();
		boolean result = userInfoDao.authentication(userName, password);
		String logData = "";
		if(result){
			logData = userName + " is logged in successfully at "+ new Date();
		}else {
			logData = userName + " cannot be logged in at "+ new Date() + "; username or password is incorrect";
		}
		loginLog.log(Level.INFO, logData);
		return result;
	}
}
